﻿using Architecture.Repository.Interface;
using Architeture.Domain;
using Architeture.Domain.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Architecture.Domain.Service
{
    public class RoleService : IRoleService
    {

        protected readonly IRoleRepository roleRep;

        public RoleService(IRoleRepository roleRep)
        {
            this.roleRep = roleRep;
        }


        public async Task<List<RoleInfoDTO>> GetRoleInfo()
        {

            var roleInfo = (await roleRep.GetAllAsync()).Select(x => new RoleInfoDTO
            {
                value = x.RoleInfoid,
                label = x.RName,
                children = null
            });
            return roleInfo.ToList();
        }

        public async Task<int> RoleAdd(RoleInfo a)
        {
            var list = (await roleRep.GetAllAsync()).FirstOrDefault(x => x.RName == a.RName && x.Isdel);
            if (list == null)
            {
                a.AddName = "张三";
                a.AddTime = DateTime.Now.ToString();
                return await roleRep.AddAsync(a);
            }
            else
            {
                return -2;
            }

        }

        public async Task<page> RoleGetAll(int pageindex, int pagesize, string? Name)
        {
            var size = (pageindex - 1) * pagesize;
            var list = (await roleRep.GetAllAsync()).Where(x => x.Isdel).ToList();
            if (Name != null)
            {
                list = list.Where(x => x.RName.Contains(Name)).ToList();
            }
            int pagecount = list.Count();
            int totalcount = (int)Math.Ceiling(pagecount * 1.0 / pagesize);
            list = list.OrderByDescending(x => x.AddTime).Skip(size).Take(pagesize).ToList();
            var page = new page();
            page.pagecount = pagecount;
            page.totalcount = totalcount;
            page.list = list;
            return page;
        }

        public async Task<RoleInfo> RoleGetById(int id)
        {
            return (await roleRep.GetAllAsync()).FirstOrDefault(x => x.RoleInfoid == id);
        }

        public async Task<int> RoleRemove(int id)
        {
            var list = (await roleRep.GetAllAsync()).FirstOrDefault(x => x.RoleInfoid == id);
            list.Isdel = false;
            return await roleRep.RoleUpd(list);
        }

        public async Task<int> RoleUpd(RoleInfo a)
        {
            a.UpdName = "李四";
            a.UpdTime = DateTime.Now.ToString();
            return await roleRep.RoleUpd(a);
        }
    }
}
